import { Module } from 'vuex'
import type { TRootState, TLoginState } from '../type'
import { mapMenusToRoutes, mapMenusToPermissions } from '@/utils/map-menus'
import router from '@/router'
import {
  accountLogin,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '@/service/login/login'
import localCache from '@/utils/cache'

const loginModule: Module<TLoginState, TRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
      userInfo: {},
      menus: [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    saveToken(state, token: string) {
      state.token = token
    },
    saveUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    saveMenus(state, menus: any) {
      state.userInfo = menus
      //根据菜单得到动态路由
      const routes = mapMenusToRoutes(menus)
      //遍历 动态添加路由到main的children中
      routes.forEach((route) => {
        router.addRoute('/main', route)
      })
      //获取按钮权限
      const permissions = mapMenusToPermissions(menus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit, dispatch }, pyload) {
      console.log('执行账号登录逻辑' + pyload.name + pyload.password)
      //登录并获取保存token
      const result = await accountLogin(pyload)
      const { id, token } = result.data
      commit('saveToken', token)
      localCache.setCache('token', token)
      // 发送初始化的请求(完整的role/department) 初始化部门和角色信息
      dispatch('getInitialDataAction', null, { root: true })
      //获取对应登录用户信息
      const userInfoAll = await requestUserInfoById(id)
      const userInfo = userInfoAll.data
      commit('saveUserInfo', userInfo)
      localCache.setCache('userInfo', userInfo)
      //获取对应用户的菜单信息
      const menusAll = await requestUserMenusByRoleId(userInfo.role.id)
      const menus = menusAll.data
      commit('saveMenus', menus)
      localCache.setCache('menus', menus)

      router.push('/main') //跳到首页
    },
    phoneLoginAction({ commit }, pyload) {
      console.log('执行手机登录逻辑' + pyload.num + pyload.code)
      console.log(commit)
    },
    loadLocalLogin({ commit, dispatch }) {
      //初始化本地数据与vuex数据联系
      const token = localCache.getCache('token')
      if (token) {
        commit('saveToken', token)
        // 发送初始化的请求(完整的role/department) 初始化部门和角色信息
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('saveUserInfo', userInfo)
      }
      const menus = localCache.getCache('menus')
      if (menus) {
        commit('saveMenus', menus)
      }
    }
  }
}

export default loginModule
